package com.doudou.oauth.config;

import com.doudou.oauth.exception.SimpleAccessDeniedHandler;
import com.doudou.oauth.exception.SimpleOAuth2AuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;

/**
 * @author 傻男人
 * @date 2020-05-06 21:31
 * @describe 资源服务器ResourceServerConfigurerAdapter
 * 同上，需要实现自己的资源服务器，继承ResourceServerConfigurerAdapter
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private DefaultTokenServices tokenServices;

    @Autowired
    private SimpleAccessDeniedHandler simpleAccessDeniedHandler;

    @Autowired
    private SimpleOAuth2AuthenticationEntryPoint simpleOAuth2AuthenticationEntryPoint;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(tokenServices);

        //异常的处理
        resources.authenticationEntryPoint(simpleOAuth2AuthenticationEntryPoint).accessDeniedHandler(simpleAccessDeniedHandler);
//        resources.addObjectPostProcessor(new ObjectPostProcessor<Object>() {
//            @Override
//            public Object postProcess(Object object) {
//                if(object instanceof OAuth2AuthenticationEntryPoint){
//                    ( (OAuth2AuthenticationEntryPoint)object).setExceptionTranslator(new SimpleWebResponseExceptionTranslator());
//                }
//                return object;
//            }
//        });
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
                .antMatchers("/me**",
                        "/oauth/corp_token**",
                        "/oauth/revoke**",
                        "/oauth/user_token**"
                )
                .and().authorizeRequests().anyRequest().authenticated();

//                http.authorizeRequests()
//                .antMatchers("/me**","/oauth/corp_token**","/oauth/revoke**","/oauth**")
//                .permitAll()
//                .anyRequest()
//                .authenticated()
//                .and().csrf().disable();

//        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }
}